package com.haixiaoke.saas.listener;


import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.OrderConstants;
import com.haixiaoke.saas.order.service.IOrderAuditRecordService;
import com.haixiaoke.saas.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Redis-key失效监听事件
 *
 * @author qixi
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderAuditRecordService orderAuditRecordService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * Redis-key失效监听事件，所有key 失效都会走此方法
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        if (StrUtil.equals("__keyevent@0__:expired", channel)) {
            String[] split = body.split(":");
            if (StrUtil.equals(split[0]+":", OrderConstants.REDIS_OBLIGATION_ORDER_KEY)) {
                log.info("订单号: " + split[1] + "超时");
                orderService.paymentTimeout(split[1]);
            } else if (StrUtil.equals(split[0]+":", OrderConstants.REDIS_AUDIT_ORDER_KEY)) {
                log.info("订单号: " + split[1] + "退订审核超时");
                orderService.reviewCancelReservationOrderTimeOut(Long.valueOf(split[1]));
            }
        } else {
            log.info("监听到其他key失效事件: " + channel);
        }
    }
}

